package com.ccut.xunfeiSpringboot.service.impl;

import com.ccut.xunfeiSpringboot.constant.Degree;
import com.ccut.xunfeiSpringboot.dto.AnalyseResumeDTO;
import com.ccut.xunfeiSpringboot.dto.ChatRequest;
import com.ccut.xunfeiSpringboot.entity.PositionInformation;
import com.ccut.xunfeiSpringboot.entity.Student;
import com.ccut.xunfeiSpringboot.entity.RecommendCareers;
import com.ccut.xunfeiSpringboot.mapper.JobMapper;
import com.ccut.xunfeiSpringboot.mapper.RecommendedJobsMapper;
import com.ccut.xunfeiSpringboot.model.RoleContent;
import com.ccut.xunfeiSpringboot.service.BaseService;
import com.ccut.xunfeiSpringboot.service.JobService;
import com.ccut.xunfeiSpringboot.service.StudentService;
import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;

@Service
public class JobServiceImpl implements JobService {

    @Autowired
    private JobMapper jobMapper;

    @Autowired
    private RecommendedJobsMapper recommendedJobsMapper;

    @Autowired
    private StudentService studentService;

    @Autowired
    private BaseService baseService;

    @Override
    public List<PositionInformation> getSelectedJobs() {
        return jobMapper.getSelectedJobs();
    }

    @Override
    public void removeJobById(Integer id) {
        jobMapper.removeJobById(id);
    }

    @Override
    public void addJob(PositionInformation job,HttpServletResponse response) throws Exception {
        jobMapper.addJob(job);
        Student student = studentService.selectById(Math.toIntExact(job.getUserId()));
        ChatRequest chatRequest = new ChatRequest();
        chatRequest.setUserId(Long.valueOf(student.getId()));
        List<RoleContent> messages = new ArrayList<>();
        messages.add(new RoleContent("system", "你是一个精通各种岗位信息的机器人，可以按照下面的信息给我推荐我以后工作的职位建议。"));
        String basePrompt = """
            请根据以下用户个人信息，以及岗位信息，生成该用户选择该岗位的优势、劣势以及建议。
            
            用户个人信息：
            - 教育背景：${educationBackground}
            - 学历：${education}
            - 技能特长：${skills}
            - 实习经历：${internshipExperience}
            - 校园经历：${campusExperience}
            - 科技竞赛：${techCompetition}
            - 自我评价：${selfEvaluation}
            - 最低期望薪资：${salary} 元/月
            - 工作的城市：${location}
            
            岗位信息：
            - 技术领域：${jobField}
            - 学历要求：${jobEducation}
            - 工作地点：${jobLocation}
            - 计划招聘人数：${recruitCount}
            - 工作所需经验：${minExperience}
            - 公司类型：${companySize}
            - 岗位名称：${jobType}
            - 最低薪资：${salaryMin}
            - 最高薪资：${salaryMax}
            - 职位描述：${jobDescription}
            - 应聘要求：${requirements}
            - 福利待遇：${benefits}
            
            输出要求：
            - 用户选择该岗位的优势
            - 用户选择该岗位的劣势
            - 用户选择该岗位的建议
            """;
        // 使用 Map 构建替换内容，仅包含用户个人信息相关字段
        Map<String, String> replacements = new HashMap<>();
        replacements.put("educationBackground", student.getEducationBackground());
        replacements.put("education", String.valueOf(Degree.fromValue(student.getRecord())));
        replacements.put("skills", student.getSkills());
        replacements.put("internshipExperience", student.getInternshipExperience());
        replacements.put("campusExperience", student.getCampusExperience());
        replacements.put("techCompetition", student.getTechCompetition());
        replacements.put("selfEvaluation", student.getSelfEvaluation());
        replacements.put("salary", student.getSalary() > 0 ? String.valueOf(student.getSalary()) : "不限");
        replacements.put("location", student.getCity() != null ? student.getCity() : "不限");
        replacements.put("jobField", job.getJobField());
        replacements.put("jobEducation", job.getEducation());
        replacements.put("jobLocation", job.getLocation());
        replacements.put("recruitCount", job.getRecruitCount());
        replacements.put("minExperience", job.getMinExperience()+"年以上");
        replacements.put("companySize", job.getCompanySize());
        replacements.put("jobType", job.getJobType());
        replacements.put("salaryMin", job.getSalaryMin()+" 元/月");
        replacements.put("salaryMax", job.getSalaryMax()+" 元/月");
        replacements.put("jobDescription", job.getJobDescription());
        replacements.put("requirements", job.getRequirements());
        replacements.put("benefits", job.getBenefits());


        String prompt = basePrompt;
        // 执行正则替换，这里只针对用户个人信息部分进行替换
        for (Map.Entry<String, String> entry : replacements.entrySet()) {
            prompt = prompt.replaceAll("\\$\\{" + entry.getKey() + "\\}", Matcher.quoteReplacement(entry.getValue()));
        }

        messages.add(new RoleContent("user", prompt));
        chatRequest.setDeepThinking(false);
        chatRequest.setNetworkSearch(false);
        chatRequest.setQuestion("");
        chatRequest.setMessages(messages);

        // 设置响应类型为 application/json 并启用流式输出
        response.setContentType("application/json;charset=UTF-8");
        response.setCharacterEncoding("UTF-8");

        ServletOutputStream outputStream = response.getOutputStream();
        baseService.chatWithStream(chatRequest,content -> {
            try {
                if (content != null) {
                    outputStream.write(content.getBytes(StandardCharsets.UTF_8));
                    outputStream.flush();
                }
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        });
    }

    @Override
    public Boolean isRecommended(Long userId) {
        List<RecommendCareers> recommendedJobs = recommendedJobsMapper.getRecommendedCareers(userId);
        return !recommendedJobs.isEmpty();
    }

    @Override
    public void recommendJobs(Integer userId, HttpServletResponse response) throws Exception {
        Student student = studentService.selectById(userId);
        ChatRequest chatRequest = new ChatRequest();
        chatRequest.setUserId(Long.valueOf(student.getId()));
        List<RoleContent> messages = new ArrayList<>();
        messages.add(new RoleContent("system", "你是一个精通各种岗位信息的机器人，可以按照下面的信息给我推荐我以后工作的技术领域、职位推荐以及职位建议。"));
        String basePrompt = """
            请根据以下用户个人信息，生成该用户所推荐的就业技术领域、职位推荐以及职位建议，并结合筛选条件提供匹配的岗位信息，优先选择用户个人信息中出现的岗位。
            
            用户个人信息：
            - 教育背景：${educationBackground}  
            - 学历：${education}  
            - 技能特长：${skills}  
            - 实习经历：${internshipExperience}  
            - 校园经历：${campusExperience}  
            - 科技竞赛：${techCompetition}
            - 自我评价：${selfEvaluation}  
            - 最低期望薪资：${salary} 元/月  
            - 工作的城市：${location}  
            
            输出字段要求（仅包含以下三项）：
            - technicalField: 技术领域（例如：人工智能、大数据、智能系统等）  
            - jobPosition: 如：技术岗、运维测试岗、产品岗等  
            - suggestion: 职位建议，需详细说明适合该用户的理由及发展建议  
            
            请以严格的 JSON 格式返回 3 个匹配的推荐岗位信息，不包含任何额外文本，可以有换行符。
            示例输出格式：
            [
              {
                "technicalField": "后端开发",
                "jobPosition": "Java开发工程师",
                "suggestion": "1. 您具备扎实的Java基础和Spring Boot框架使用经验，适合从事后端开发相关工作.\\n2. 拥有大型公司实习经历，建议优先考虑中大型互联网企业提升技术深度.\\n3. 可进一步深入学习微服务架构与分布式系统，提升系统设计能力。"
              },
              {
                "technicalField": "软件工程与架构",
                "jobPosition": "高级软件开发工程师",
                "suggestion": "1. 您在ACM竞赛中展现出优秀的算法与逻辑思维能力，适合挑战更高阶的开发岗位.\\n2. 具备良好的团队协作与组织能力，可向技术负责人方向发展.\\n3. 建议加强系统架构设计能力，并关注云原生与DevOps相关技术趋势。"
              }
            ]
            """;
        String prompt = basePrompt;
        // 使用 Map 构建替换内容，仅包含用户个人信息相关字段
        Map<String, String> replacements = new HashMap<>();
        replacements.put("educationBackground", student.getEducationBackground());
        replacements.put("education", String.valueOf(Degree.fromValue(student.getRecord())));
        replacements.put("skills", student.getSkills());
        replacements.put("internshipExperience", student.getInternshipExperience());
        replacements.put("campusExperience", student.getCampusExperience());
        replacements.put("techCompetition", student.getTechCompetition());
        replacements.put("selfEvaluation", student.getSelfEvaluation());
        replacements.put("salary", student.getSalary() > 0 ? String.valueOf(student.getSalary()) : "不限");
        replacements.put("location", student.getCity() != null ? student.getCity() : "不限");

        // 执行正则替换，这里只针对用户个人信息部分进行替换
        for (Map.Entry<String, String> entry : replacements.entrySet()) {
            prompt = prompt.replaceAll("\\$\\{" + entry.getKey() + "\\}", Matcher.quoteReplacement(entry.getValue()));
        }

        messages.add(new RoleContent("user", prompt));
        chatRequest.setDeepThinking(false);
        chatRequest.setNetworkSearch(false);
        chatRequest.setQuestion("");
        chatRequest.setMessages(messages);

        // 设置响应类型为 application/json 并启用流式输出
        response.setContentType("application/json;charset=UTF-8");
        response.setCharacterEncoding("UTF-8");

        ServletOutputStream outputStream = response.getOutputStream();
        baseService.streamJobSuggestions(chatRequest,content -> {
            try {
                if (content != null) {
                    outputStream.write(content.getBytes(StandardCharsets.UTF_8));
                    outputStream.flush();
                }
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        });
    }

    @Override
    public List<RecommendCareers> getRecommendedCareers(Integer userId) {
        return recommendedJobsMapper.getRecommendedCareers(Long.valueOf(userId));
    }

    @Override
    public void searchRecommendedJobs(Integer userId , HttpServletResponse response) throws Exception {
        List<RecommendCareers> recommendedCareers = recommendedJobsMapper.getRecommendedCareers(Long.valueOf(userId));
        Student student = studentService.selectById(userId);
        ChatRequest chatRequest = new ChatRequest();
        chatRequest.setUserId(Long.valueOf(student.getId()));
        List<RoleContent> messages = new ArrayList<>();
        messages.add(new RoleContent("system", "你是一个精通各种岗位信息的机器人，可以按照下面的信息给我推荐我以后工作的技术领域、职位推荐以及职位建议。"));

        // 使用 Map 构建替换内容，仅包含用户个人信息相关字段
        Map<String, String> replacements = new HashMap<>();
        replacements.put("educationBackground", student.getEducationBackground());
        replacements.put("education", String.valueOf(Degree.fromValue(student.getRecord())));
        replacements.put("skills", student.getSkills());
        replacements.put("internshipExperience", student.getInternshipExperience());
        replacements.put("campusExperience", student.getCampusExperience());
        replacements.put("techCompetition", student.getTechCompetition());
        replacements.put("selfEvaluation", student.getSelfEvaluation());
        replacements.put("salary", student.getSalary() > 0 ? String.valueOf(student.getSalary()) : "不限");
        replacements.put("location", student.getCity() != null ? student.getCity() : "不限");

        // 构建 technicalFields 和 jobPositions 字符串
        StringBuilder technicalFieldsBuilder = new StringBuilder();
        StringBuilder jobPositionsBuilder = new StringBuilder();

        for (int i = 0; i < recommendedCareers.size(); i++) {
            RecommendCareers career = recommendedCareers.get(i);
            if (i > 0) {
                technicalFieldsBuilder.append(", ");
                jobPositionsBuilder.append(", ");
            }
            technicalFieldsBuilder.append(career.getTechnicalField());
            jobPositionsBuilder.append(career.getJobPosition());
        }

        replacements.put("technicalFields", technicalFieldsBuilder.toString());
        replacements.put("jobPositions", jobPositionsBuilder.toString());

        String basePrompt = """
        请根据以下筛选条件，提供匹配的5个岗位信息，5个岗位信息的公司规模要包含大型公司、中型公司、小微企业三种类型，并以严格的 JSON 格式返回结果，不要包含任何额外文本。

        筛选条件：
        - 教育背景：${educationBackground}
        - 学历：${education}
        - 技能特长：${skills}
        - 实习经历：${internshipExperience}
        - 校园经历：${campusExperience}
        - 科技竞赛：${techCompetition}
        - 自我评价：${selfEvaluation}
        - 最低期望薪资：${salary} 元/月
        - 工作的城市：${location}

        输出字段要求：
        - jobField: 岗位名称，在[${technicalFields}]中选择
        - location: 工作地点，在${location}中选择
        - minExperience: 最低工作经验要求（单位为年，整数，例如：3）
        - companySize: 公司规模（大型公司/中型公司/小微企业）
        - jobType: 岗位类别，在[${jobPositions}]中选择
        - salaryMin: 最低薪资（单位为元，整数，例如：8000）
        - salaryMax: 最高薪资（单位为元，整数，例如：12000）
        - education: 学历要求
        - recruitCount: 招聘人数（单位为人，整数，例如：6）
        - jobDescription: 职位描述，需要详细
        - requirements: 应聘要求，需要详细
        - benefits: 岗位福利，需要详细
        
        输出格式示例，可以有换行符：
        [
          {
            "jobFiled": "Java开发工程师",
            "location": "北京",
            "minExperience": 3,
            "companySize": "大型公司",
            "jobType": "技术岗",
            "salaryMin": 8000,
            "salaryMax": 12000,
            "education": "本科",
            "recruitCount": "5",
            "jobDescription": "1. 负责后端系统的设计与开发工作\\n2. 参与需求评审和技术方案讨论\\n3. 编写高质量和可维护的代码",
            "requirements": "1. 熟悉Spring Boot框架\\n2. 具备良好的编码规范\\n3. 熟练掌握MySQL数据库优化"
            "benefits": "1. 奖金\\n2. 旅游\\n3. 零食\\n4. 医疗\\n5. 公积金"
          }
        ]
        """;

        // 执行正则替换，这里只针对用户个人信息部分进行替换
        String prompt = basePrompt;
        for (Map.Entry<String, String> entry : replacements.entrySet()) {
            prompt = prompt.replaceAll("\\$\\{" + entry.getKey() + "\\}", Matcher.quoteReplacement(entry.getValue()));
        }

        messages.add(new RoleContent("user", prompt));

        chatRequest.setDeepThinking(false);
        chatRequest.setNetworkSearch(false);
        chatRequest.setQuestion("");
        chatRequest.setMessages(messages);

        // 设置响应类型为 application/json 并启用流式输出
        response.setContentType("application/json;charset=UTF-8");
        response.setCharacterEncoding("UTF-8");

        ServletOutputStream outputStream = response.getOutputStream();
        baseService.searchJobs(chatRequest, content -> {
            try {
                if (content != null) {
                    outputStream.write(content.getBytes(StandardCharsets.UTF_8));
                    outputStream.flush();
                }
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        });
    }

    @Override
    public List<PositionInformation> getInterviewedJobs(Integer userId) {
        return jobMapper.getInterviewedJobs(userId);
    }

    @Override
    public List<PositionInformation> getNotInterviewedJobs(Integer userId) {
        return jobMapper.getNotInterviewedJobs(userId);
    }

    @Override
    public void removeRecommendedCarreeer(Long id) {
        recommendedJobsMapper.removeRecommendedCarreeer(id);
    }

    @Override
    public void updateJob(Long id) {
        jobMapper.updateJob(id);
    }

    @Override
    public void addRecommendedCareer(RecommendCareers recommendCareers, HttpServletResponse response) throws Exception {
        Student student = studentService.selectById(Math.toIntExact(recommendCareers.getUserId()));
        ChatRequest chatRequest = new ChatRequest();
        chatRequest.setUserId(Long.valueOf(student.getId()));
        List<RoleContent> messages = new ArrayList<>();
        messages.add(new RoleContent("system", "你是一个精通各种岗位信息的机器人，可以按照下面的信息给我推荐我以后工作的职位建议。"));
        String basePrompt = """
            请根据以下用户个人信息，生成该用户的职位建议。
            
            用户个人信息：
            - 教育背景：${educationBackground}
            - 学历：${education}
            - 技能特长：${skills}
            - 实习经历：${internshipExperience}
            - 校园经历：${campusExperience}
            - 科技竞赛：${techCompetition}
            - 自我评价：${selfEvaluation}
            - 最低期望薪资：${salary} 元/月
            - 工作的城市：${location}
            
            输出字段要求（仅包含以下三项）：
            - technicalField: 严格返回${technicalField}
            - jobPosition: 严格返回${jobPosition}
            - suggestion: 职位建议，需详细说明适合该用户的理由及发展建议
            
            请以严格的 JSON 格式返回该推荐岗位信息，technicalField字段严格返回${technicalField}，jobPosition字段严格返回${jobPosition}，不包含任何额外文本，可以有换行符。
            示例输出格式：
            [
              {
                "technicalField": ${technicalField},
                "jobPosition": ${jobPosition},
                "suggestion": "1. 您具备扎实的Java基础和Spring Boot框架使用经验，适合从事后端开发相关工作.\\n2. 拥有大型公司实习经历，建议优先考虑中大型互联网企业提升技术深度.\\n3. 可进一步深入学习微服务架构与分布式系统，提升系统设计能力。"
              }
            ]
            """;
        // 使用 Map 构建替换内容，仅包含用户个人信息相关字段
        Map<String, String> replacements = new HashMap<>();
        replacements.put("educationBackground", student.getEducationBackground());
        replacements.put("education", String.valueOf(Degree.fromValue(student.getRecord())));
        replacements.put("skills", student.getSkills());
        replacements.put("internshipExperience", student.getInternshipExperience());
        replacements.put("campusExperience", student.getCampusExperience());
        replacements.put("techCompetition", student.getTechCompetition());
        replacements.put("selfEvaluation", student.getSelfEvaluation());
        replacements.put("salary", student.getSalary() > 0 ? String.valueOf(student.getSalary()) : "不限");
        replacements.put("location", student.getCity() != null ? student.getCity() : "不限");
        replacements.put("technicalField", recommendCareers.getTechnicalField());
        replacements.put("jobPosition", recommendCareers.getJobPosition());

        String prompt = basePrompt;
        // 执行正则替换，这里只针对用户个人信息部分进行替换
        for (Map.Entry<String, String> entry : replacements.entrySet()) {
            prompt = prompt.replaceAll("\\$\\{" + entry.getKey() + "\\}", Matcher.quoteReplacement(entry.getValue()));
        }

        messages.add(new RoleContent("user", prompt));
        chatRequest.setDeepThinking(false);
        chatRequest.setNetworkSearch(false);
        chatRequest.setQuestion("");
        chatRequest.setMessages(messages);

        // 设置响应类型为 application/json 并启用流式输出
        response.setContentType("application/json;charset=UTF-8");
        response.setCharacterEncoding("UTF-8");

        ServletOutputStream outputStream = response.getOutputStream();
        baseService.streamJobSuggestions(chatRequest,content -> {
            try {
                if (content != null) {
                    outputStream.write(content.getBytes(StandardCharsets.UTF_8));
                    outputStream.flush();
                }
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        });
    }

    @Override
    public void changeRecommendedCareer(Integer userId, HttpServletResponse response) throws Exception {
        Student student = studentService.selectById(userId);
        ChatRequest chatRequest = new ChatRequest();
        chatRequest.setUserId(Long.valueOf(student.getId()));
        List<RoleContent> messages = new ArrayList<>();
        messages.add(new RoleContent("system", "你是一个精通各种岗位信息的机器人，可以按照下面的信息给我推荐我以后工作的技术领域、职位推荐以及职位建议。"));
        String basePrompt = """
            请根据以下用户个人信息，生成该用户所推荐的就业技术领域、职位推荐以及职位建议，并结合筛选条件提供匹配的岗位信息。  
            
            用户个人信息：
            - 教育背景：${educationBackground}  
            - 学历：${education}  
            - 技能特长：${skills}  
            - 实习经历：${internshipExperience}  
            - 校园经历：${campusExperience}  
            - 科技竞赛：${techCompetition}
            - 自我评价：${selfEvaluation}  
            - 最低期望薪资：${salary} 元/月  
            - 工作的城市：${location}  
            
            输出字段要求（仅包含以下三项）：
            - technicalField: 技术领域（例如：人工智能、大数据、物联网、智能系统等）  
            - jobPosition: 如：技术岗、运维测试岗、产品岗等  
            - suggestion: 职位建议，需详细说明适合该用户的理由及发展建议  
            
            要求不能与已有的推荐的职业方向相同，已有的职业方向：{careers}
            
            请以严格的 JSON 格式返回 1 个匹配的推荐岗位信息，不包含任何额外文本，可以有换行符。
            示例输出格式：
            [
              {
                "technicalField": "后端开发",
                "jobPosition": "Java开发工程师",
                "suggestion": "1. 您具备扎实的Java基础和Spring Boot框架使用经验，适合从事后端开发相关工作.\\n2. 拥有大型公司实习经历，建议优先考虑中大型互联网企业提升技术深度.\\n3. 可进一步深入学习微服务架构与分布式系统，提升系统设计能力。"
              }
            ]
            """;
        String prompt = basePrompt;
        // 使用 Map 构建替换内容，仅包含用户个人信息相关字段
        Map<String, String> replacements = new HashMap<>();
        replacements.put("educationBackground", student.getEducationBackground());
        replacements.put("education", String.valueOf(Degree.fromValue(student.getRecord())));
        replacements.put("skills", student.getSkills());
        replacements.put("internshipExperience", student.getInternshipExperience());
        replacements.put("campusExperience", student.getCampusExperience());
        replacements.put("techCompetition", student.getTechCompetition());
        replacements.put("selfEvaluation", student.getSelfEvaluation());
        replacements.put("salary", student.getSalary() > 0 ? String.valueOf(student.getSalary()) : "不限");
        replacements.put("location", student.getCity() != null ? student.getCity() : "不限");
        prompt = prompt.replace("{careers}", recommendedJobsMapper.getRecommendedCareers(Long.valueOf(userId)).toString());

        // 执行正则替换，这里只针对用户个人信息部分进行替换
        for (Map.Entry<String, String> entry : replacements.entrySet()) {
            prompt = prompt.replaceAll("\\$\\{" + entry.getKey() + "\\}", Matcher.quoteReplacement(entry.getValue()));
        }

        messages.add(new RoleContent("user", prompt));
        chatRequest.setDeepThinking(false);
        chatRequest.setNetworkSearch(false);
        chatRequest.setQuestion("");
        chatRequest.setMessages(messages);

        // 设置响应类型为 application/json 并启用流式输出
        response.setContentType("application/json;charset=UTF-8");
        response.setCharacterEncoding("UTF-8");

        ServletOutputStream outputStream = response.getOutputStream();
        baseService.streamJobSuggestions(chatRequest,content -> {
            try {
                if (content != null) {
                    outputStream.write(content.getBytes(StandardCharsets.UTF_8));
                    outputStream.flush();
                }
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        });
    }

    @Override
    public void changeJob(Integer userId, HttpServletResponse response) throws Exception {
        List<RecommendCareers> recommendedCareers = recommendedJobsMapper.getRecommendedCareers(Long.valueOf(userId));
        Student student = studentService.selectById(userId);
        ChatRequest chatRequest = new ChatRequest();
        chatRequest.setUserId(Long.valueOf(student.getId()));
        List<RoleContent> messages = new ArrayList<>();
        messages.add(new RoleContent("system", "你是一个精通各种岗位信息的机器人，可以按照下面的信息给我推荐我以后工作的技术领域、职位推荐以及职位建议。"));

        // 使用 Map 构建替换内容，仅包含用户个人信息相关字段
        Map<String, String> replacements = new HashMap<>();
        replacements.put("educationBackground", student.getEducationBackground());
        replacements.put("education", String.valueOf(Degree.fromValue(student.getRecord())));
        replacements.put("skills", student.getSkills());
        replacements.put("internshipExperience", student.getInternshipExperience());
        replacements.put("campusExperience", student.getCampusExperience());
        replacements.put("techCompetition", student.getTechCompetition());
        replacements.put("selfEvaluation", student.getSelfEvaluation());
        replacements.put("salary", student.getSalary() > 0 ? String.valueOf(student.getSalary()) : "不限");
        replacements.put("location", student.getCity() != null ? student.getCity() : "不限");

        // 构建 technicalFields 和 jobPositions 字符串
        StringBuilder technicalFieldsBuilder = new StringBuilder();
        StringBuilder jobPositionsBuilder = new StringBuilder();

        for (int i = 0; i < recommendedCareers.size(); i++) {
            RecommendCareers career = recommendedCareers.get(i);
            if (i > 0) {
                technicalFieldsBuilder.append(", ");
                jobPositionsBuilder.append(", ");
            }
            technicalFieldsBuilder.append(career.getTechnicalField());
            jobPositionsBuilder.append(career.getJobPosition());
        }

        replacements.put("technicalFields", technicalFieldsBuilder.toString());
        replacements.put("jobPositions", jobPositionsBuilder.toString());

        String basePrompt = """
        请根据以下筛选条件，提供匹配的1个岗位信息，并以严格的 JSON 格式返回结果，不要包含任何额外文本。

        筛选条件：
        - 教育背景：${educationBackground}
        - 学历：${education}
        - 技能特长：${skills}
        - 实习经历：${internshipExperience}
        - 校园经历：${campusExperience}
        - 科技竞赛：${techCompetition}
        - 自我评价：${selfEvaluation}
        - 最低期望薪资：${salary} 元/月
        - 工作的城市：${location}

        输出字段要求：
        - jobField: 岗位名称，在[${technicalFields}]中选择
        - location: 工作地点，在${location}中选择
        - minExperience: 最低工作经验要求（单位为年，整数，例如：3）
        - companySize: 公司规模（大型公司/中型公司/小微企业）
        - jobType: 岗位类别，在[${jobPositions}]中选择
        - salaryMin: 最低薪资（单位为元，整数，例如：8000）
        - salaryMax: 最高薪资（单位为元，整数，例如：12000）
        - education: 学历要求
        - recruitCount: 招聘人数（单位为人，整数，例如：6）
        - jobDescription: 职位描述，需要详细
        - requirements: 应聘要求，需要详细
        - benefits: 岗位福利，需要详细
        
        输出格式示例，可以有换行符：
        [
          {
            "jobFiled": "Java开发工程师",
            "location": "北京",
            "minExperience": 3,
            "companySize": "大型公司",
            "jobType": "技术岗",
            "salaryMin": 8000,
            "salaryMax": 12000,
            "education": "本科",
            "recruitCount": "5",
            "jobDescription": "1. 负责后端系统的设计与开发工作\\n2. 参与需求评审和技术方案讨论\\n3. 编写高质量和可维护的代码",
            "requirements": "1. 熟悉Spring Boot框架\\n2. 具备良好的编码规范\\n3. 熟练掌握MySQL数据库优化"
            "benefits": "1. 奖金\\n2. 旅游\\n3. 零食\\n4. 医疗\\n5. 公积金"
          }
        ]
        """;

        // 执行正则替换，这里只针对用户个人信息部分进行替换
        String prompt = basePrompt;
        for (Map.Entry<String, String> entry : replacements.entrySet()) {
            prompt = prompt.replaceAll("\\$\\{" + entry.getKey() + "\\}", Matcher.quoteReplacement(entry.getValue()));
        }

        messages.add(new RoleContent("user", prompt));

        chatRequest.setDeepThinking(false);
        chatRequest.setNetworkSearch(false);
        chatRequest.setQuestion("");
        chatRequest.setMessages(messages);

        // 设置响应类型为 application/json 并启用流式输出
        response.setContentType("application/json;charset=UTF-8");
        response.setCharacterEncoding("UTF-8");

        ServletOutputStream outputStream = response.getOutputStream();
        baseService.searchJobs(chatRequest, content -> {
            try {
                if (content != null) {
                    outputStream.write(content.getBytes(StandardCharsets.UTF_8));
                    outputStream.flush();
                }
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        });
    }

    @Override
    public AnalyseResumeDTO analyseResume(Integer userId) throws Exception {
        List<RecommendCareers> recommendedCareers = recommendedJobsMapper.getRecommendedCareers(Long.valueOf(userId));
        Student student = studentService.selectById(userId);
        ChatRequest chatRequest = new ChatRequest();
        chatRequest.setUserId(Long.valueOf(student.getId()));
        List<RoleContent> messages = new ArrayList<>();
        messages.add(new RoleContent("system", "你是一个精通各种岗位信息的机器人，可以按照下面的信息给我推荐我以后工作的技术领域、职位推荐以及职位建议。"));

        // 使用 Map 构建替换内容，仅包含用户个人信息相关字段
        Map<String, String> replacements = new HashMap<>();
        replacements.put("educationBackground", student.getEducationBackground());
        replacements.put("education", String.valueOf(Degree.fromValue(student.getRecord())));
        replacements.put("skills", student.getSkills());
        replacements.put("internshipExperience", student.getInternshipExperience());
        replacements.put("campusExperience", student.getCampusExperience());
        replacements.put("techCompetition", student.getTechCompetition());
        replacements.put("selfEvaluation", student.getSelfEvaluation());
        replacements.put("salary", student.getSalary() > 0 ? String.valueOf(student.getSalary()) : "不限");
        replacements.put("location", student.getCity() != null ? student.getCity() : "不限");

        // 构建 technicalFields 和 jobPositions 字符串
        StringBuilder technicalFieldsBuilder = new StringBuilder();
        StringBuilder jobPositionsBuilder = new StringBuilder();

        for (int i = 0; i < recommendedCareers.size(); i++) {
            RecommendCareers career = recommendedCareers.get(i);
            if (i > 0) {
                technicalFieldsBuilder.append(", ");
                jobPositionsBuilder.append(", ");
            }
            technicalFieldsBuilder.append(career.getTechnicalField());
            jobPositionsBuilder.append(career.getJobPosition());
        }

        replacements.put("technicalFields", technicalFieldsBuilder.toString());
        replacements.put("jobPositions", jobPositionsBuilder.toString());

        String basePrompt = """
            请根据以下用户的简历信息，从以下五个维度进行评分（每项评分为0到100之间的整数）：
            - 专业技能
            - 工作经验
            - 团队协作
            - 问题解决
            - 沟通能力
            
            并以严格的 JSON 格式返回评分结果，不要包含任何额外文本。
        
            简历信息：
            - 教育背景：${educationBackground}
            - 学历：${education}
            - 技能特长：${skills}
            - 实习经历：${internshipExperience}
            - 校园经历：${campusExperience}
            - 科技竞赛：${techCompetition}
            - 自我评价：${selfEvaluation}
        
            输出字段要求：
            - 该简历的优缺点：要分析优点以及缺点，并且分点展示，优缺点的序号都从1开始
            - professionalSkills: 专业技能评分（0-100）
            - workExperience: 工作经验评分（0-100）
            - teamwork: 团队协作评分（0-100）
            - problemSolving: 问题解决评分（0-100）
            - communication: 沟通能力评分（0-100）
        
            输出格式示例：
            {
              "evaluation": "**优点**：\\n1.该学生在团队协作能力方面比较出众\\n**缺点**：\\n1.该学生在工作经验上稍显不足，还需努力"
              "professionalSkills": "85",
              "workExperience": "76",
              "teamwork": "90",
              "problemSolving": "82",
              "communication": "88"
            }
            """;

        // 执行正则替换，这里只针对用户个人信息部分进行替换
        String prompt = basePrompt;
        for (Map.Entry<String, String> entry : replacements.entrySet()) {
            prompt = prompt.replaceAll("\\$\\{" + entry.getKey() + "\\}", Matcher.quoteReplacement(entry.getValue()));
        }

        messages.add(new RoleContent("user", prompt));

        chatRequest.setDeepThinking(false);
        chatRequest.setNetworkSearch(false);
        chatRequest.setQuestion("");
        chatRequest.setMessages(messages);
        return baseService.analyseResume(chatRequest);
    }

    @Override
    public Boolean userIsInterviewed(Integer userId) {
        return !jobMapper.getInterviewedJobs(userId).isEmpty();
    }

}
